<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2025-03-18 11:53:48
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-03-24 15:51:10
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\businessAnalysis\incomeStatistics\components\incomeSummary.vue
-->
<template>
  <div class="incomestatic">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :inline="true" @keyup.enter="searchFn">
        <el-form-item label="统计日期：">
          <pb-date-picker v-model="planDateRang" placeholder="请输入" @change="dateChange"></pb-date-picker>
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="divide-css"></div>
    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <ContentOperation>
          <pb-button size="small" plain @click="downStatisticFN" v-hasPerm="'center:Analysis:hz-export'">导出</pb-button>
        </ContentOperation>
        <div class="main-box">
          <el-table :data="tableData" border :height="tableHeight" :span-method="spanMethod"
            :summary-method="getSummaries" show-summary>
            <template v-for="(item, index) in tabHeader.headersFir" :key="index">
              <el-table-column :label="item.name" width="120" v-if="item.hasChildHeader == 0">
                <template #default="{ row }">
                  {{ row[item.key] }}
                </template>
              </el-table-column>
              <el-table-column :label="item.name" width="120" align="center" v-else>
                <template v-for="(sec, ind) in tabHeader.headersSec[item.key]" :key="ind">
                  <el-table-column :label="sec.name" :prop="sec.key" align="right">
                    <template #default="{ row }">
                      {{ row[item.key][sec.key] }}
                    </template>
                  </el-table-column>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </pb-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from "dayjs"
import { getIncomeSummary, DownincomesummaryApi } from '@/api/incomeStatistics'

const downStatisticFN = () => {
  DownincomesummaryApi({
    ...incomeForm.value
  }).then(response => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
    } else {
      decodedFilename = "食堂消费统计" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}


const formOrigin = () => ({
  statisticsStartDate: dayjs().startOf('week').format('YYYY-MM-DD'),
  statisticsStopDate: dayjs().endOf('week').format('YYYY-MM-DD'),
});
const incomeForm = ref(formOrigin());
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());

// 设置时间
const planDateRang = ref([incomeForm.value.statisticsStartDate, incomeForm.value.statisticsStopDate])
const dateChange = () => {
  incomeForm.value.statisticsStartDate = dayjs(planDateRang.value[0]).format('YYYY-MM-DD')
  incomeForm.value.statisticsStopDate = dayjs(planDateRang.value[1]).format('YYYY-MM-DD')
}

const searchFn = () => {
  getTableList()
}
const resetFn = () => {
  incomeForm.value = formOrigin()
  pages.value = pageInit()
  getTableList()
}


const tableColumn = reactive([
  {
    key: 'index',
    name: '序号',
    width: 50,
  },
  {
    key: "tenantName",
    name: "单位名称",
  },
  {
    key: "statisticsDate",
    name: "登记日期",
    width: 70
  },
  {
    key: "totalAmount",
    name: "总金额（元）",
    align: 'right',
  },
  {
    key: "incomeSourceName",
    name: "收入来源",
  },
  {
    key: "incomeCategoryName",
    name: "收入类型",
  },
  {
    key: "incomeAmount",
    name: "收入金额(元)",
    align: 'right',
  },
  {
    key: "dinersCount",
    name: "就餐人次",
    align: 'right',
  },
  {
    key: "deliveryFee",
    name: "配送费",
    align: 'right',
  },
  {
    key: "creator",
    name: "创建人",
  },
  {
    key: "createTime",
    name: "创建时间",
  },

])


// 计算指定列的合并信息
const computeCell = (tableList, mergeKeys) => {
  const cellList = [];
  let count = 0;
  let prevKey = null;
  for (let i = 0; i < tableList.length; i++) {
    // 生成合并键（序号 + 需要合并的列）
    const currentKey = mergeKeys.map(key => tableList[i][key]).join('|');
    if (i === 0) {
      cellList.push(1);
      count = 0;
      prevKey = currentKey;
    } else {
      if (currentKey === prevKey) {
        cellList[count]++;
        cellList.push(0);
      } else {
        cellList.push(1);
        count = i;
        prevKey = currentKey;
      }
    }
  }
  return cellList;
};

// 合并方法
const spanMethod = ({ rowIndex, columnIndex }) => {
  const columns = tabHeader.value.headersFir.map(col => col.key);
  const column = columns[columnIndex];

  // 定义各列的合并规则
  const mergeRules = {
    h1_index: ['h1_index'],
    h1_center: ['h1_index', 'h1_center'],
  };

  if (mergeRules[column]) {
    const cellList = computeCell(tableData.value, mergeRules[column]);
    const fRow = cellList[rowIndex];
    return {
      rowspan: fRow,
      colspan: fRow > 0 ? 1 : 0
    };
  }

  return { rowspan: 1, colspan: 1 };
};

const getSummaries = ({ columns, data }: any) => {
  const sums = [] as any;
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      sums[index] = '汇总';
      return;
    }
    if (column.property) {
      const values = data.map(el => {
        for (const key in el) {
          if (el[key][column.property]) {
            return Number(el[key][column.property])
          }
        }
      })
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return parseFloat((prev + curr).toFixed(2));
        } else {
          return prev;
        }
      }, 0);
    }
  });
  return sums;
}

const tabHeader = ref({})
const tableData = ref([])
const getTableList = () => {
  getIncomeSummary({
    ...incomeForm.value
  }).then(res => {
    if (res.code == 2000) {

      tableData.value = res.data.dataMap
      tabHeader.value = {
        headersFir: res.data.headersFir,
        headersSec: res.data.headersSec
      }
    }
  })
}



// 计算table高度
const customHeight = ref(0)
const tableHeight = ref(0)
const getHeight = () => {
  const table = document.getElementsByClassName("el-table");
  if (table.length == 0) return

  // height为table到视图顶部的距离
  const height = table[0].getBoundingClientRect().top;
  customHeight.value = height + 40
  tableHeight.value = window.innerHeight - customHeight.value;
}

onMounted(() => {
  getTableList()
  nextTick(() => {
    getHeight()
  })
  window.addEventListener("resize", getHeight, true);
})
</script>
<style lang="scss" scoped>
::v-deep .el-table__footer-wrapper {
  height: 50px;
  background: rgba(0, 0, 0, 0.04);

  .table__footer {
    height: 100%;
  }
}

::v-deep thead {
  th {
    background: #F5F5F5 !important;
    // padding: 9px 16px !important;
  }
}

::v-deep .el-table__body {

  td:last-child {
    border-right: none;

  }
}

::v-deep .cell {
  // padding: 0px
}

::v-deep tfoot tr td {
  background: #F5F5F5 !important;
  // padding: 15px 16px !important;
}


// 表格右边框线
.el-table--border::after {
  width: 0;
}

// 表格上边框线
:deep(.el-table__inner-wrapper::after) {
  height: 0;
}


// 表格左边框线
.el-table::before {
  width: 0;
}

:deep(.el-table__border-left-patch) {
  width: 0;
}
</style>